<template>
  <div class="link-page">
    <el-button
      slot="label"
      class="add-btn"
      plain
      type="primary"
      size="medium"
      icon="el-icon-plus"
      @click="visible = true"
    >新增</el-button>
    <!-- 顶部标签页 -->
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <!-- 文字链接表格 -->
      <el-tab-pane label="文字链接" name="text">
        <el-table :data="tableData" border>
          <el-table-column
            label="#"
            type="index"
            width="50px"
          />
          <el-table-column prop="title" label="标题" />
          <el-table-column prop="des" label="链接描述" />
          <el-table-column prop="type" label="链接类型">
            <template slot-scope="scope">
              <el-tag v-if="+scope.row.type === 1">文字类型</el-tag>
              <el-tag v-else>图片类型</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="url" label="链接地址" />
          <el-table-column label="操作" align="center">
            <template #default="{ row }">
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="handlerEdit('edit', row.id)"
              />
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="handlerDel(row.id)"
              />
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <lay-page
          :limit.sync="queryData.limit"
          :page.sync="queryData.page"
          :count="count"
        />
      </el-tab-pane>

      <!-- 图片链接表格 -->
      <el-tab-pane label="图片链接" name="img">
        <el-table :data="tableData" border>
          <el-table-column
            label="#"
            type="index"
            width="50px"
          />
          <el-table-column prop="des" label="链接描述" />
          <el-table-column prop="img" label="链接图片">
            <template slot-scope="scope">
              <el-image
                v-if="scope.row.img"
                style="width: 120px; height: 60px"
                :src="$ImgUrl + scope.row.img"
                fit="fill"
              />
            </template>
          </el-table-column>
          <el-table-column prop="type" label="链接类型">
            <template slot-scope="scope">
              <el-tag v-if="+scope.row.type === 1">文字类型</el-tag>
              <el-tag v-else type="success">图片类型</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="url" label="链接地址" />
          <el-table-column label="操作" align="center">
            <template #default="{ row }">
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="handlerEdit('edit', row.id)"
              />
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="handlerDel(row.id)"
              />
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <lay-page
          :limit.sync="queryData.limit"
          :page.sync="queryData.page"
          :count="count"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 对话================================ -->
    <el-dialog :visible.sync="visible" width="45%" :before-close="handleClose">
      <!-- 表单 -->
      <div slot="title" class="header-title">
        <!-- <div>添加分类</div> -->
        <div>添加友情链接</div>
      </div>
      <el-form
        ref="formRef"
        label-width="120px"
        size="medium"
        :model="formData"
        :rules="rules"
      >
        <el-form-item label="链接类型" prop="type">
          <el-select v-model="formData.type" size="medium">
            <el-option value="1" label="文字链接" />
            <el-option value="2" label="图片链接" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="+formData.type === 1" label="标题" prop="title">
          <el-input
            v-model="formData.title"
            placeholder="请输入链接地址名称"
          />
        </el-form-item>
        <el-form-item label="链接地址" prop="url">
          <el-input
            v-model="formData.url"
            placeholder="请输入链接地址名称"
          />
        </el-form-item>
        <el-form-item label="链接描述" prop="des">
          <el-input v-model="formData.des" type="textarea" />
        </el-form-item>
        <el-form-item v-if="+formData.type === 2" label="链接图片" prop="img">
          <el-upload
            ref="upload"
            class="upload-demo"
            action="http://124.223.14.236:8060/admin/common/upload?type=images"
            :limit="1"
            :file-list="fileList"
            list-type="picture"
            auto-upload
            :headers="headerObj"
            :on-change="fileChange"
            :on-remove="fileRemove"
            :on-success="fileSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" autofocus @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getLinkListApi, addLinkApi, delLinkApi, getLinkInfo, editLinkApi } from '@/api/link'
import { getToken } from '@/utils/storage'
export default {
  name: 'LinkPage',
  data() {
    return {
      activeName: 'text', // 标签页
      queryData: {
        type: '1',
        page: 1,
        limit: 10
      },
      count: 0,
      tableData: [],
      visible: false,
      formData: {
        des: '',
        img: '',
        title: '',
        type: '',
        url: ''
      },
      rules: {
        des: [
          {
            required: true,
            message: '链接描述类型必须！',
            trigger: ['blur']
          }
        ],
        type: [
          { required: true, message: '链接地址类型必须！', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '链接地址类型必须！', trigger: 'blur' }
        ],
        title: [{ required: true, message: '标题类型必须！', trigger: 'blur' }],
        img: [
          {
            required: true,
            message: '链接图片类型必须！',
            trigger: ['blur', 'change']
          }
        ]
      },
      fileList: [],
      headerObj: {
        'X-Token': getToken()
      }
    }
  },
  // 分页
  watch: {
    'queryData.limit'(val) {
      this.initData()
    },
    'queryData.page'(val) {
      this.initData()
    }

  },
  created() {
    this.initData()
  },
  methods: {
    // 标签页点击事件
    handleClick(tab, event) {
      if (tab.index === '0') {
        console.log('text')
        this.queryData = {
          type: '1',
          page: 1,
          limit: 10
        }
      } else {
        console.log('img')
        this.queryData = {
          type: '2',
          page: 1,
          limit: 10
        }
      }
      this.initData()
    },
    async initData() {
      const res = await getLinkListApi(this.queryData)
      this.tableData = res.data
      this.count = res.count
    },

    // 关闭对话框
    handleClose(done) {
      // console.log(111)
      this.$confirm('确认关闭？')
        .then((_) => {
          this.dialogClose()
        })
        .catch((_) => {})
    },
    // 关闭对话框 清空表单
    dialogClose() {
      this.visible = false
      this.formData = {
        des: '',
        img: '',
        title: '',
        type: '',
        url: ''
      }
      // 清空文件列表
      if (+this.formData.type === 2) this.$refs.upload.clearFiles()
      // 清空表单校验
      this.$refs.formRef.clearValidate()
    },
    // 表单提交
    async submit() {
      try {
        await this.$refs.formRef.validate()
        this.formData.id ? await editLinkApi(this.formData) : await addLinkApi(this.formData)
        this.$message.success(this.formData.id ? '修改成功！' : '添加成功！')
        this.dialogClose()
        this.initData()
      } catch (err) {
        console.log(err)
      }
    },
    // 文件发生改变触发
    fileChange(uploadFile, fileList) {
      if (fileList.length === 0) return
      this.$refs.formRef.validateField('img')
    },
    // 文件删除触发
    fileRemove(uploadFile, fileList) {
      console.log(fileList.length)
      // this.btnisShow = true
      this.formData.img = ''
      this.$refs.formRef.validateField('img')
    },
    // 文件上传成功触发
    fileSuccess(response, file, fileList) {
      this.formData.img = response.data.savePath
    },
    // 删除
    handlerDel(id) {
      this.$confirm('确认删除？')
        .then(async(_) => {
          await delLinkApi(id)
          this.$message.success('删除成功！')
          if (this.queryData.page > 1 && this.tableData.length === 1) {
            this.pageData.page--
          }
          this.initData()
        })
        .catch((_) => {})
    },
    // 编辑回显
    async handlerEdit(type, id) {
      // this.$refs.formRef.clearValidate()
      this.fileList = []
      this.visible = true
      const res = await getLinkInfo(id)
      // console.log(res)
      // 回显的数组
      this.fileList.push({ url: this.$ImgUrl + res.img })
      this.formData = {
        ...res
      }
    }
  }
}
</script>

<style lang="less" scoped>
.link-page {
  position: relative;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
}

.add-btn {
  position: absolute;
  right: 20px;
  top: 20px;
  cursor: pointer;
  z-index: 1000;
}
.el-table {
  margin-top: 10px;
}

/deep/.el-dialog__header {
  background: #fafafa;
}
</style>
